package masterjava.common.client.gwt;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import masterjava.common.shared.state.StateException;
import org.jetbrains.annotations.Nullable;

/**
 * User: gkislin
 * Date: 7/22/11
 */
public class ExceptionHandler {
    private static ExceptionHandler INSTANCE = new ExceptionHandler();

    public static void treatException(Throwable e) {
        treatException(null, e);
    }

    public static void treatException(@Nullable String context, Throwable e) {
        if (e instanceof StateException) {
            context = "State error";
        } else if (context == null) {
            context = "Application exception";
        }
        GWT.log(context + " (" + e.toString() + ")", e);
        get().getExceptionHandler().treatException(context, e);
    }

    private IExceptionHandler exceptionHandler = new IExceptionHandler() {
        @Override
        public void treatException(@Nullable String context, Throwable e) {
            Window.alert(context + "(" + e.getMessage() + ")");
        }
    };

    public static ExceptionHandler get() {
        return INSTANCE;
    }

    public IExceptionHandler getExceptionHandler() {
        return exceptionHandler;
    }

    public void setExceptionHandler(IExceptionHandler exceptionHandler) {
        this.exceptionHandler = exceptionHandler;
    }

    private ExceptionHandler() {
    }
}
